﻿using my_webapi_demo.Common;
using my_webapi_demo.Db;
using my_webapi_demo.Db.Entity;

namespace my_webapi_demo.Tast;

/// <summary>
/// 数据库初始化，创建种子数据
/// </summary>
public class DbInitializationTask : HuaskyTask
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        using var db = new HuaskyDbContext();
        try
        {
            if (await db.Database.EnsureCreatedAsync(stoppingToken))
            {
                LoggerHelper.Info("--数据库创建完成--");
                var seeds = DIHelper.CreateAll<ISeedData>();
                foreach (var seed in seeds)
                {
                    var type = seed.GetType();
                    var properties = type.GetProperties();
                    foreach (var property in properties)
                    {
                        var val = (IEnumerable<DbEntity>)property.GetValue(seed);
                        await db.AddRangeAsync(val, stoppingToken);
                    }
                }
                await db.SaveChangesAsync(stoppingToken);
                LoggerHelper.Info("--系统数据初始化完成--");
            }
        }
        catch (Exception ex)
        {
            LoggerHelper.Error(ex, "数据库初始化操作异常");
        }
    }
}


